package com.yjy.lab03.service;

import com.yjy.lab03.model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class RegionStatsService {

    private String lastTime;
    private final String uriTemplate = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private final List<RegionStats> regionStatsList = new ArrayList<>();
    private List<RegionStats> statsList;
    public List<RegionStats> getAllRegionStats(){
        return regionStatsList;
    }
    public List<RegionStats> getAllStatsList(){
        return statsList;
    }
    @PostConstruct
    @Scheduled(cron = "0 0 5 * * *")
    public void UpdateRegionStatsList() {
        //爬取数据
        int count = 0;
        RestTemplate template = new RestTemplate();
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(uriTemplate))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36")
                .build();
        ResponseEntity<Resource> exchange = template.exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        Reader in = null;
        //将数据封装到List中的RegionStats里
        try {
            in =  new InputStreamReader(new BufferedInputStream(body.getInputStream()));
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
            for (CSVRecord record : records) {
                if(count==0){
                    String[] str = record.get(record.size()-1).split("/");
                    lastTime = "20"+str[2]+"年"+str[0]+"月"+str[1]+"日";
                }
                else {
                    RegionStats regionStats = new RegionStats();
                    regionStats.setState(record.get(0));
                    regionStats.setCountry(record.get(1));
                    regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
                    regionStats.setIncreaseFromPrevDay(Math.max(0,Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2))));
                    regionStatsList.add(regionStats);
                }
                ++count;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
//根据输入字符串查找相关数据
    public List<RegionStats> search(String str){
        Stream<RegionStats> stream = regionStatsList.parallelStream();
        statsList = stream.filter(re -> re.getCountry().contains(str)||re.getState().contains(str)).collect(Collectors.toList());
        Optional<Integer> sum = regionStatsList.parallelStream().map(re -> re.getLatestTotalCases()).reduce((d1, d2) -> d1+d2);
        return statsList;
    }

    //获取最新统计时间
    public String getLastTime(){
        return lastTime;
    }

    public int getSum(){
       Optional<Integer> sum = regionStatsList.parallelStream().map(re -> re.getLatestTotalCases()).reduce((d1, d2) -> d1+d2);
        return sum.get();
    }

}
